import functools
import re
import sys

import requests


def mycmp1(x, y):  # 升序排列
    return x["cues"][0]["time"] - y["cues"][0]["time"]


def mycmp2(x, y):  # 升序排列
    return x["time"] - y["time"]


def mycmp3(x, y):  # 升序排列
    return x[0] - y[0]


def down_load_translate(name):
    en_url = f"https://www.ted.com/talks/{name}/transcript.json?language=en"
    cn_url = f"https://www.ted.com/talks/{name}/transcript.json?language=zh-cn"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
                      "(KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
    }
    en_res = requests.get(en_url, headers=headers)
    cn_res = requests.get(cn_url, headers=headers)

    en_paragraphs = en_res.json()["paragraphs"]
    en_paragraphs.sort(key=functools.cmp_to_key(mycmp1))
    cn_paragraphs = cn_res.json()["paragraphs"]
    cn_paragraphs.sort(key=functools.cmp_to_key(mycmp1))

    en_list = []
    for en_p in en_paragraphs:
        cues_list = en_p["cues"]
        for c in cues_list:
            en_list.append(c)
    en_list.sort(key=functools.cmp_to_key(mycmp2))

    cn_list = []
    for cn_p in cn_paragraphs:
        cues_list = cn_p["cues"]
        for c in cues_list:
            cn_list.append(c)
    cn_list.sort(key=functools.cmp_to_key(mycmp2))

    if len(en_list) != len(cn_list):
        if len(en_paragraphs) != len(cn_paragraphs):
            return
        else:
            for x in range(len(en_paragraphs)):
                en_cues_list = en_paragraphs[x]["cues"]
                en_cues_list.sort(key=functools.cmp_to_key(mycmp2))
                for en_cue in en_cues_list:
                    text_ = en_cue["text"].replace("\n", " ")
                    print(text_, end=' ')
                print("")

                cn_cues_list = cn_paragraphs[x]["cues"]
                cn_cues_list.sort(key=functools.cmp_to_key(mycmp2))
                for cn_cue in cn_cues_list:
                    text_ = cn_cue["text"].replace("\n", " ")
                    print(text_, end=' ')
                print("")

        return

    time_cn_dict = {}

    for i in range(len(en_list)):
        en_cue = en_list[i]
        cn_cue = cn_list[i]
        time_cn_dict[en_cue["time"]] = cn_cue["text"]

    for i in range(len(en_paragraphs)):
        cues_en = en_paragraphs[i]["cues"]
        cues_en.sort(key=functools.cmp_to_key(mycmp2))
        for j in range(len(cues_en)):
            text_ = cues_en[j]["text"].replace("\n", " ")
            print(text_, end=' ')
        print("")

        for j in range(len(cues_en)):
            text_ = time_cn_dict[cues_en[j]["time"]]
            text_ = text_.replace("\n", " ")
            print(text_, end=' ')
        print("")


if __name__ == "__main__":
    arg1 = sys.argv[1]
    down_load_translate(arg1)
